import store from '@/store'
import nedb from '@/db/nedb'

// import base64 from '../utils/base64'

/**
 * 返回指定微信的朋友圈信息 ok
 */
function circlePushNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('返回指定微信ID的朋友圈信息：CirclePushNotice')
  // console.log(msg)
  // console.log(message)
  // 如果有朋友圈数据
  if (message.Circles) {
    // console.log('有朋友圈')
    let count = message.Count || 0 // 返回的朋友圈总数
    let size = message.Size // 每页返回的朋友圈 最大值
    let page = message.Page || 0 // 页
    let length = message.Circles.length || 0 // 当前页实际的朋友圈数量
    let userId = store.getters.userId // 当前用户
    let Owner = message.WeChatId // 发起任务的微信id
    let i = 0

    // 遍历朋友圈存入数据库
    for (const circle of message.Circles) {
      circle.user = userId
      circle.Owner = Owner
      circle.Liked = false // 发起任务的微信是否给该朋友圈点赞

      // 是否点赞
      if (circle.Likes) {
        for (const like of circle.Likes) {
          if (like.FriendId === Owner) {
            circle.Liked = true
          }
        }
      }

      nedb.circles.update(
        {
          user: userId,
          CircleId: circle.CircleId,
          WeChatId: circle.WeChatId,
          Owner: Owner
        },
        { $set: circle },
        { upsert: true },
        err => {
          if (!err) {
            i++
            if (size * page + length >= count && i === length) {
              // console.log(`${Owner}推送完成`)
              if (circle.WeChatId === Owner) {
                // console.log('我的朋友圈')
                store.dispatch('circles/SetWechatCircles', Owner)
              } else {
                // console.log('好友的朋友圈')
                store.dispatch('conversation/SetFriendCircles', circle.WeChatId)
              }
            }
          } else {
            console.log(err)
          }
          store.dispatch('SetDialog', '')
        }
      )
    }
  } else {
    console.log('获取不到朋友圈')
    store.dispatch('SetDialog', '')
  }
}

/**
 * 发送朋友圈结果通知 ok
 */
function postSNSNewsTaskResultNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('朋友圈发送结果通知：PostSNSNewsTaskResultNotice')
  // console.log(message)
  // 发送成功 应该要按微信号分别判断 这里没有这么些 需要自己改
  store.dispatch('SetDialog', '')
  if (message.Success) {
    nedb.circleTask.update(
      { user: store.getters.userId, TaskId: Number(message.TaskId) },
      { $set: { CircleId: message.Extra.CircleId, result: 1 } },
      {},
      (err, count) => {
        console.log(err || count)
      }
    )
  }
}

/**
 * 朋友圈删除通知 ok
 */
function circleDelNoticeHandle (msg) {
  // console.log('朋友圈删除通知：CircleDelNotice')
  let message = JSON.parse(msg.message)
  // console.log(message)
  let userId = store.getters.userId
  // 从本地删除数据
  nedb.circles.remove(
    { user: userId, CircleId: message.CircleId, Owner: message.WeChatId },
    {},
    err => {
      let currentCirclesWechat = store.getters['circles/wechatId']
      if (
        !err &&
        currentCirclesWechat &&
        currentCirclesWechat === message.WeChatId
      ) {
        store.dispatch('circles/SetWechatCircles', message.WeChatId)
      }
    }
  )
}

/**
 * 新朋友圈通知 ok
 */
function circleNewPublishNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('新朋友圈通知：circleNewPublishNoticeHandle')
  // console.log(message)
  let doc = message.Circle
  doc.Owner = message.WeChatId
  doc.Liked = false
  doc.user = store.getters.userId
  nedb.circles.insert(doc, (err, newDoc) => {
    let currentCirclesWechat = store.getters['circles/wechatId']
    if (
      !err &&
      currentCirclesWechat &&
      currentCirclesWechat === message.WeChatId
    ) {
      store.dispatch('circles/SetWechatCircles', message.WeChatId)
    }
  })
}

/**
 * 获取朋友圈图片详情 ok
 */
function circleDetailNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('获取朋友圈图片详情：circleDetailNoticeHandle')
  // console.log(message)
  nedb.circles.update(
    {
      user: store.getters.userId,
      CircleId: message.Circle.CircleId,
      WeChatId: message.Circle.WeChatId,
      Owner: message.WeChatId
    },
    { $set: { Content: message.Circle.Content } },
    { upsert: true },
    err => {
      if (!err) {
        if (message.WeChatId === message.Circle.WeChatId) {
          store.dispatch('circles/SetWechatCircles', message.WeChatId)
        } else {
          store.dispatch(
            'conversation/SetFriendCircles',
            message.Circle.WeChatId
          )
        }
        store.dispatch('SetDialog', '')
      }
    }
  )
}

/**
 * 朋友圈点赞推送 ok
 * 取消点赞不会推送
 */
function circleLikeNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('朋友圈点赞推送：circleLikeNoticeHandle')
  // console.log(message)
  let doc = {
    FriendId: message.FriendId,
    PublishTime: message.PublishTime
  }
  // console.log(doc)

  // 是否存在
  nedb.circles.findOne(
    { user: store.getters.userId, CircleId: message.CircleId },
    (err, fdoc) => {
      if (!err && fdoc) {
        let likes = fdoc.Likes === undefined ? [] : fdoc.Likes
        let flag = true
        // 是否已保存点赞
        for (const like of likes) {
          if (like.FriendId === message.FriendId) {
            flag = false
          }
        }
        // 如果没有保存点赞信息
        if (flag) {
          likes.push(doc)
          nedb.circles.update(
            { user: store.getters.userId, CircleId: message.CircleId },
            { $set: { Likes: likes } },
            (err, replaceNum) => {
              console.log(err || replaceNum)
              store.dispatch('circles/SetWechatCircles', '')
            }
          )
        }
      }
    }
  )
}

/**
 * 评论推送 ok
 */
function circleCommentNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('新评论通知：circleCommentNoticeHandle')
  // console.log(message)
  nedb.circles.findOne(
    {
      user: store.getters.userId,
      CircleId: message.CircleId,
      Owner: message.WeChatId
    },
    (err, doc) => {
      if (message.IsDelete && !err && doc) {
        // console.log('删除评论推送')
        // if (!err && doc) {
        let comments = []
        for (const comment of doc.Comments) {
          if (comment.CommentId !== message.Comment.CommentId) {
            comments.push(comment)
          }
        }
        nedb.circles.update(
          { user: store.getters.userId, CircleId: message.CircleId },
          { $set: { Comments: comments } },
          { upsert: false },
          err => {
            if (!err && doc.Owner === doc.WeChatId) {
              store.dispatch('circles/SetWechatCircles', '')
            } else if (!err) {
              store.dispatch('conversation/SetFriendCircles', doc.WeChatId)
            }
          }
        )
        // }
      } else if (!err) {
        // console.log('新增评论推送')
        nedb.circles.update(
          { CircleId: message.CircleId, Owner: message.WeChatId },
          { $addToSet: { Comments: message.Comment } },
          { upsert: false },
          err => {
            if (!err && doc.Owner === doc.WeChatId) {
              store.dispatch('circles/SetWechatCircles', '')
            } else if (!err) {
              store.dispatch('conversation/SetFriendCircles', doc.WeChatId)
            }
          }
        )
      }
    }
  )
}

/**
 * 朋友圈评论结果 ok
 */
function circleCommentReplyTaskResultNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  // console.log('朋友圈评论结果通知：circleCommentReplyTaskResultNoticeHandle')
  // console.log(message)
  // 更新task
  let flag = message.Success ? 1 : 2
  nedb.circleTask.update(
    { user: store.getters.userId, TaskId: Number(message.TaskId) },
    { $set: { result: flag } },
    {},
    err => {
      console.log(err || 'task更新成功')
    }
  )
  store.dispatch('SetDialog', '')

  // 更新本地nedb
  if (message.Success) {
    nedb.circleTask.findOne(
      {
        user: store.getters.userId,
        TaskId: Number(message.TaskId)
      },
      (err, doc) => {
        console.log(err || '有数据')
        // console.log(doc)
        if (!err && doc) {
          let comment = {
            CommentId: message.CommentId,
            Content: doc.Content,
            FromWeChatId: message.WeChatId,
            PublishTime: message.PusblishTime
          }
          if (message.ReplyCommentId) {
            comment.ReplyCommentId = message.ReplyCommentId
            comment.ToWeChatId = doc.ToWeChatId
          }
          // console.log(comment)
          nedb.circles.update(
            {
              user: store.getters.userId,
              CircleId: message.CircleId,
              Owner: message.WeChatId
            },
            { $addToSet: { Comments: comment } },
            { upsert: true },
            err => {
              // console.log(err || '更新本地circles成功')
              if (!err && doc.WeChatId === doc.friendId) {
                console.log('my circle')
                store.dispatch('circles/SetWechatCircles', '')
              } else if (!err) {
                console.log('friend Circle')
                store.dispatch('conversation/SetFriendCircles', doc.friendId)
              }
            }
          )
        }
      }
    )
  }
}

/**
 * 删除朋友圈评论 ok
 */
function circleCommentDeleteTaskResultNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  console.log(
    '删除朋友圈评论结果通知：circleCommentDeleteTaskResultNoticeHandle'
  )
  console.log(message)
  // 更新任务表
  let flag = message.Success ? 1 : 2
  nedb.circleTask.update(
    { user: store.getters.userId, TaskId: Number(message.TaskId) },
    { $set: { result: flag } },
    {},
    (err, count) => {
      console.log(err || count)
    }
  )
  // 更新本地circle
  if (message.Success) {
    nedb.circleTask.findOne(
      {
        user: store.getters.userId,
        TaskId: Number(message.TaskId)
      },
      (err, doc) => {
        if (!err && doc) {
          console.log(doc)
          console.log(doc.Comments)
          let comments = []
          for (const comment of doc.Comments) {
            if (comment.CommentId !== message.CommentId) {
              comments.push(comment)
            }
          }
          if (comments.length === 0) {
            nedb.circles.update(
              {
                user: store.getters.userId,
                CircleId: message.CircleId,
                Owner: message.WeChatId
              },
              { $unset: { Comments: {} } },
              { upsert: false },
              err => {
                if (!err && doc.WeChatId === doc.friendId) {
                  console.log('my circle')
                  store.dispatch('circles/SetWechatCircles', '')
                } else if (!err) {
                  console.log('friend Circle')
                  store.dispatch('conversation/SetFriendCircles', doc.friendId)
                }
              }
            )
          } else {
            nedb.circles.update(
              { user: store.getters.userId, CircleId: message.CircleId },
              { $set: { Comments: comments } },
              { upsert: false },
              err => {
                if (!err && doc.WeChatId === doc.friendId) {
                  console.log('my circle')
                  store.dispatch('circles/SetWechatCircles', '')
                } else if (!err) {
                  console.log('friend Circle')
                  store.dispatch('conversation/SetFriendCircles', doc.friendId)
                }
              }
            )
          }
        }
      }
    )
  }

  store.dispatch('SetDialog', '')
}

export default {
  circleDelNoticeHandle,
  circlePushNoticeHandle,
  postSNSNewsTaskResultNoticeHandle,
  circleDetailNoticeHandle,
  circleLikeNoticeHandle,
  circleCommentReplyTaskResultNoticeHandle,
  circleCommentDeleteTaskResultNoticeHandle,
  circleCommentNoticeHandle,
  circleNewPublishNoticeHandle
}
